package com.yang.crawler.article.executor;

import com.yang.crawler.CrawlArticleCommand;
import com.yang.crawler.common.BusinessException;
import com.yang.crawler.common.ResultCode;
import com.yang.crawler.dto.data.ArticleDTO;
import com.yang.crawler.strategy.IArticleCrawlStrategy;
import com.yang.crawler.strategy.dto.ArticleCrawlDTO;
import com.yang.crawler.strategy.factory.ArticleCrawlStrategyFactory;
import com.yang.crawler.strategy.request.ArticleCrawlRequest;
import org.springframework.stereotype.Component;

@Component
public class CrawArticleCmdExecutor {
    public ArticleDTO execute(CrawlArticleCommand crawlArticleCommand) {
        String website = crawlArticleCommand.getWebsite();
        IArticleCrawlStrategy articleReptileStrategy = ArticleCrawlStrategyFactory.getArticleCrawlStrategy(website);
        if (articleReptileStrategy == null) {
            throw new BusinessException(ResultCode.WEBSITE_NOT_SUPPORT);
        }
        String columnTitle = crawlArticleCommand.getColumnTitle();
        String articleUrl = crawlArticleCommand.getArticleUrl();

        ArticleCrawlRequest articleReptileRequest = new ArticleCrawlRequest();
        articleReptileRequest.setArticleUrl(articleUrl);
        articleReptileRequest.setColumnTitle(columnTitle);
        articleReptileRequest.setWebsite(website);
        ArticleCrawlDTO articleCrawlDTO = articleReptileStrategy.crawlArticle(articleReptileRequest);

        return convert2ArticleDTO(website, crawlArticleCommand.getColumnTitle(), articleCrawlDTO);
    }

    private ArticleDTO convert2ArticleDTO(String website, String columnTitle, ArticleCrawlDTO articleCrawlDTO) {
        ArticleDTO articleDTO = new ArticleDTO();
        articleDTO.setWebsite(website);
        articleDTO.setColumnTitle(columnTitle);
        articleDTO.setTitle(articleCrawlDTO.getTitle());
        articleDTO.setArticleUrl(articleCrawlDTO.getLink());
        articleDTO.setHtmlContent(articleCrawlDTO.getHtmlContent());
        return articleDTO;
    }
}
